package com.example.hotel.controller;

import com.example.hotel.pojo.Result;
import com.example.hotel.pojo.User;
import com.example.hotel.service.UserService;
import com.example.hotel.utils.JwtUtil;
import com.example.hotel.utils.Md5Util;
import jakarta.validation.constraints.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/login")
    public Result<String> login(@RequestParam("username") String username, @RequestParam("password") String password){
        System.out.printf("username: "+username);
        System.out.println("");
        System.out.printf("password: "+password);
        System.out.println("");
        User user = userService.findByUserName(username);
        if(user==null)return Result.error("用户不存在!!");
        //System.out.println(user);
        //判断密码是否正确
        if (Md5Util.getMD5String(password).equals(user.getPassword())){

            Map<String,Object> claims = new HashMap<>();
            claims.put("id",user.getId());
            claims.put("username",user.getUsername());
            //生成token令牌
            String token = JwtUtil.genToken(claims);

            //把token存储到redis中
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(token,token,1, TimeUnit.HOURS);
            return Result.success(token);
        }
        //密码错误
        return Result.error("用户名或密码错误!!");
        //return Result.success("后台接收到!!");
    }

    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {

        //查询用户
        User u = userService.findByUserName(username);
        if (u == null) {
            //没有占用
            //注册
            userService.register(username, password);
            return Result.success();
        } else {
            //占用
            return Result.error("用户名已被占用");
        }
    }
}
